<template>
  <div class="tabs" v-if="MultiPage">
    <div class="tab" :class="{ 'on': currentType == 0 }" @click="handletab(0)">页面</div>
    <div class="tab" :class="{ 'on': currentType == 1 }" @click="handletab(1)">图层</div>
  </div>
  <Thumbnails v-if='currentType === 0' class="layout-content-page" />
  <ul class="layer-pool" v-else>
    <div class="item" v-for="(item,index) in slides" :key="index">
      <div class="page" :class="{'on': slideIndex === index}">
        <h2 @click="handleClickTitle(index)">
          <i class="appIcon-iconfont appIcon-xiangzuo" :class="{'bottom': slideIndex === index}"></i>
          <span>第{{index + 1}}页</span>
        </h2>
        <div class="elements" :class="{'hide': slideIndex !== index}">
          <dd v-for="(j,i) in item.elements" :key="i" @click="handleClickElement(j)" :class="{'on': handleElementId === j.id || (activeElementIdList.includes(j.id) && !j.groupId),
           'group' : j.groupId,
          }" @mousedown="($event) => getCurrentCustomId($event, j)" v-contextmenu="contextmenusThumbnails">
            <dl :class="`group${j.groupId}`">
              <span v-if="j.type === 'text'"><i class="appIcon-iconfont appIcon-wenzimoren"></i>文字</span>
              <span v-else-if="j.type === 'image'"><i
                  class="appIcon-iconfont appIcon-tuxingzujian-yunpantupianmoren"></i>图片</span>
              <span v-else-if="j.type === 'video'"><i
                  class="appIcon-iconfont appIcon-tuxingzujian-yunpanshipinmoren"></i>视频</span>
              <span v-else-if="j.type === 'shape'"><i class="appIcon-iconfont appIcon-xingzhuangmoren"></i>形状</span>
              <span v-else-if="j.type === 'line'">
                <IconConnection />线条
              </span>
              <span v-else-if="j.type === 'chart'"><i class="appIcon-iconfont appIcon-tubiaomoren1"></i>图表</span>
              <span v-else-if="j.type === 'table'">
                <IconInsertTable />表格
              </span>
              <span v-else-if="j.type === 'latex'">
                <IconFormula />公式
              </span>
            </dl>
            <div class="eye" @click.stop="handleEye(j)">
              <i class="appIcon-iconfont appIcon-anliyulan show" v-if="!j.hide"></i>
              <i class="appIcon-iconfont appIcon-tuceng-yincang hide" v-if="j.hide"></i>
            </div>
          </dd>
        </div>
      </div>
    </div>

  </ul>
</template>

<script lang="ts">
import { computed, defineComponent, onMounted, onUnmounted, reactive, ref, watch } from 'vue'
import { getElementListRange } from '@/utils/element'
import { storeToRefs } from 'pinia'
import { ContextmenuItem } from '@/components/Contextmenu/types'
import useSlideHandler from '@/hooks/useSlideHandler'
// import useSelectElement from '@/hooks/useSelectElement'

import useLockElement from '@/hooks/useLockElement'
import useDeleteElement from '@/hooks/useDeleteElement'
import useCombineElement from '@/hooks/useCombineElement'
import useOrderElement from '@/hooks/useOrderElement'
import useAlignElementToCanvas from '@/hooks/useAlignElementToCanvas'
import useCopyAndPasteElement from '@/hooks/useCopyAndPasteElement'
import useSelectAllElement from '@/hooks/useSelectAllElement'
import { ElementOrderCommands, ElementAlignCommands } from '@/types/edit'
import useHistorySnapshot from '@/hooks/useHistorySnapshot'

import { useMainStore, useSlidesStore, useKeyboardStore } from '@/store'
// import request from '@/utils/request'
import { message } from 'ant-design-vue'
import emitter, { EmitterEvents } from '@/utils/emitter'
import Thumbnails from '@/views/Editor/Thumbnails/index.vue'

export default defineComponent({
  name: 'layer-pool',
  emits: ['select'],
  components: {
    Thumbnails,
  },
  setup(props, { emit }) {
    const currentType = ref(1)
    const { canvasScale, customList,handleElement, handleElementId, handleGroupId, activeElementIdList, EditorType } = storeToRefs(useMainStore())
    const slidesStore = useSlidesStore()
    const { addHistorySnapshot } = useHistorySnapshot()
    
    const { slides, slideIndex, currentSlide } = storeToRefs(useSlidesStore())
    // const { } = useSelectElement()
    const { ctrlKeyState, ctrlOrShiftKeyActive } = storeToRefs(useKeyboardStore())
    const MultiPage = ref(false)
    watch(
      () => EditorType.value,
      (val: any) => {
        if(val == '2' || val == '3') { //自由编辑器和ppt显示多页面
          MultiPage.value = true
        }
      },
      {immediate: true}
    )
    const { 
      scrollToCurrent,
    } = useSlideHandler()
    const handleClickTitle = (index: any) => {
      slidesStore.updateSlideIndex(index)
      scrollToCurrent()
    }
    const handletab = (i: number) => {
      currentType.value = i
    }
    const setGroupColor = () => {
      let colorArr = ['#79BEFF','#FFC069','#576EE7','#EA7BD9','#43DAE2','#67DEB4']
      let arr: any = []
      // groupID列表
      currentSlide.value.elements.map((item: any) => {
        (item.groupId && !arr.includes(item.groupId)) ? arr.push(item.groupId) : ''
      })
      // 每组加颜色
      arr.forEach((item: any, index: any) => {
        let el = document.querySelectorAll('.group'+item) as unknown as HTMLElement[] 
        let color = colorArr[index % colorArr.length]
        for(let i = 0; i < el.length; i++) {
          el[i].style.borderColor = color;
          (el[i].querySelector('i,.i-icon') as HTMLElement).style.color = color
        }
      })
    }
    onMounted(() => {
      setGroupColor()
    })
    watch(
      () => currentSlide.value,
      (val) => {
        setGroupColor()
      },{ immediate: true, deep: true}
    )
    const handleClickElement = (item: any) => {
      
      useMainStore().setCurrentTab(0)
      if(item.groupId) {
        useMainStore().setHandleGroupId(item.groupId)
        let arr: any = []
        currentSlide.value.elements.filter((item: any, index: any) => item.groupId === handleGroupId.value)
        .forEach((item:any) => {
          arr.push(item.id)
        })
        useMainStore().setActiveElementIdList(arr)
        useMainStore().setActiveGroupElementId(item.id)
        useMainStore().setHandleElementId(item.id)
      } else {
        useMainStore().setHandleGroupId('')

        if(ctrlOrShiftKeyActive.value) {
          !activeElementIdList.value.includes(item.id) ? activeElementIdList.value.push(item.id) : ''
          
          useMainStore().setActiveElementIdList(activeElementIdList.value)
          useMainStore().setHandleElementId(item.id)
        } else {
          useMainStore().setActiveElementIdList([item.id])
        }
      }

    }
    const updateHideOrShow = (props: any) => {
      if (!handleElement.value) return
      slidesStore.updateElement({ id: handleElement.value.id, props })
      addHistorySnapshot()
    }
    const handleEye = (item: any) => {
      handleClickElement(item)
      updateHideOrShow({hide: !item.hide })
    }
    const currentElementInfo = ref()  //当前元素
    const isMultiSelect = ref()       //是否是组合状态
    const openLinkDialog = ref()      //是否打开添加链接
    const getCurrentCustomId = (e: MouseEvent, item: any) => {
      if(activeElementIdList.value.length <= 1) {
        handleClickElement(item)
      } 

      currentElementInfo.value = item
      
      // activeElementIdList
      // if(item.groupId) {
      //   useMainStore().setHandleGroupId(item.groupId)
      //   useMainStore().setActiveElementIdList([])
      // } else {
      //   useMainStore().setHandleGroupId('')
      //   useMainStore().setActiveElementIdList([item.id])
      // }
    }
    
    const { orderElement } = useOrderElement()
    const { alignElementToCanvas } = useAlignElementToCanvas()
    const { combineElements, uncombineElements } = useCombineElement()
    const { deleteElement } = useDeleteElement()
    const { lockElement, unlockElement } = useLockElement()
    const { copyElement, pasteElement, cutElement } = useCopyAndPasteElement()
    const { selectAllElement } = useSelectAllElement()

    const contextmenusThumbnails = (): ContextmenuItem[] => {      
      if (currentElementInfo.value.lock) {
        return [{
          text: '解锁', 
          handler: () => unlockElement(currentElementInfo.value),
        }]
      }
      
      let menusList = [
        {
          text: '剪切',
          subText: 'Ctrl + X',
          handler: cutElement,
        },
        {
          text: '复制',
          subText: 'Ctrl + C',
          handler: copyElement,
        },
        {
          text: '粘贴',
          subText: 'Ctrl + V',
          handler: pasteElement,
        },
        { divider: true },
        {
          text: '水平居中',
          handler: () => alignElementToCanvas(ElementAlignCommands.HORIZONTAL),
          children: [
            { text: '水平垂直居中', handler: () => alignElementToCanvas(ElementAlignCommands.CENTER), },
            { text: '水平居中', handler: () => alignElementToCanvas(ElementAlignCommands.HORIZONTAL) },
            { text: '左对齐', handler: () => alignElementToCanvas(ElementAlignCommands.LEFT) },
            { text: '右对齐', handler: () => alignElementToCanvas(ElementAlignCommands.RIGHT) },
          ],
        },
        {
          text: '垂直居中',
          handler: () => alignElementToCanvas(ElementAlignCommands.VERTICAL),
          children: [
            { text: '水平垂直居中', handler: () => alignElementToCanvas(ElementAlignCommands.CENTER) },
            { text: '垂直居中', handler: () => alignElementToCanvas(ElementAlignCommands.VERTICAL) },
            { text: '顶部对齐', handler: () => alignElementToCanvas(ElementAlignCommands.TOP) },
            { text: '底部对齐', handler: () => alignElementToCanvas(ElementAlignCommands.BOTTOM) },
          ],
        },
        { divider: true },
        {
          text: '置于顶层',
          disable: activeElementIdList.value.length > 1 && !currentElementInfo.value.groupId,
          handler: () => orderElement(currentElementInfo.value, ElementOrderCommands.TOP),
          children: [
            { text: '置于顶层', handler: () => orderElement(currentElementInfo.value, ElementOrderCommands.TOP) },
            { text: '上移一层', handler: () => orderElement(currentElementInfo.value, ElementOrderCommands.UP) },
          ],
        },
        {
          text: '置于底层',
          disable: activeElementIdList.value.length > 1 && !currentElementInfo.value.groupId,
          handler: () => orderElement(currentElementInfo.value, ElementOrderCommands.BOTTOM),
          children: [
            { text: '置于底层', handler: () => orderElement(currentElementInfo.value, ElementOrderCommands.BOTTOM) },
            { text: '下移一层', handler: () => orderElement(currentElementInfo.value, ElementOrderCommands.DOWN) },
          ],
        },
        { divider: true },
        {
          text: '设置链接',
          handler: openLinkDialog.value,
        },
        {
          text: currentElementInfo.value.groupId ? '取消组合' : '组合',
          subText: 'Ctrl + G',
          handler: currentElementInfo.value.groupId ? uncombineElements : combineElements,
          hide: activeElementIdList.value.length <= 1,
        },
        {
          text: '全选',
          subText: 'Ctrl + A',
          handler: selectAllElement,
        },
        {
          text: '锁定',
          subText: 'Ctrl + L',
          handler: lockElement,
        },
        {
          text: '删除',
          subText: 'Delete',
          handler: deleteElement,
        },
      ]
      if (currentElementInfo.value.groupId) {
        menusList.unshift({
          text: '保存为自定义组件',
          handler: () => saveCustom(currentElementInfo.value),
        })
      }
      return menusList
    }
    const saveCustom = (data: any) => {
      emitter.emit(EmitterEvents.CREATE_CUSTOM)
    }
    return {
      slides,
      slideIndex,
      handleClickTitle,
      handleClickElement,
      handleElementId,
      handleGroupId,
      contextmenusThumbnails,
      getCurrentCustomId,
      currentElementInfo,
      isMultiSelect,
      openLinkDialog,
      activeElementIdList,
      setGroupColor,
      updateHideOrShow,
      handleEye,
      currentType,
      handletab,
      MultiPage
    }
  },
})
</script>

<style lang="scss" scoped>
.tabs {
  display: flex;
  margin-bottom: 17px;
  // border-bottom: 1px solid $contentBorderColor;

  .tab {
    flex: 1;
    text-align: center;
    color: #fff;
    line-height: 40px;
    font-size: 18px;
    cursor: pointer;

    &::after {
      position: absolute;
      display: block;
      content: '';
      width: 16px;
      height: 3px;
      background: #a6a9ff;
      border-radius: 2px;
      bottom: 0;
      left: 50%;
      margin-left: -8px;
      opacity: 0;
      transform: translateX(50px);
      transition: .2s transform cubic-bezier(0.38, 0.8, 0.32, 1.07);
    }

    &:nth-child(2)::after {
      transform: translateX(-50px);
    }

    &.on {
      color: #a6a9ff;
      position: relative;

      &::after {
        opacity: 1;
        transform: translateX(0);
      }
    }
  }
}

.layer-pool {
  padding: 0 15px;
  margin-top: 20px;
}

.item {
  .page {
    &.on {
      h2 {
        background: #313343;
        border-radius: 4px;
      }
    }

    h2 {
      font-size: 16px;
      color: #fff;
      height: 42px;
      line-height: 42px;
      padding: 0 10px;
      display: flex;
      align-items: center;
      cursor: pointer;

      span {
        padding-left: 10px;
      }

      i {
        font-size: 12px;
        display: block;
        line-height: 42px;
        transition: .5s all ease;

        &.bottom {
          transform: rotate(90deg);
        }
      }
    }

    .elements {
      font-size: 16px;
      color: #AFACC7;
      transition: .5s all ease;
      height: 100%;
      margin: 5px 0;

      &.hide {
        display: none;
        overflow: hidden;
      }

      dd {
        height: 42px;
        line-height: 42px;
        cursor: pointer;
        position: relative;

        dl {
          padding-left: 30px;
        }

        .eye {
          position: absolute;
          right: 10px;
          top: 0;

          i {
            color: #AFACC7;
            transform: scale(0);
            display: block;
            transition: .5s all ease;
          }

          .hide {
            transform: scale(1);
          }
        }

        &.group {
          background: #0e0e1e;
          border-radius: 0;

          dl {
            border-left: 3px solid #686CE8;
          }
        }

        &.on {
          background: #313343;
          border-radius: 4px;
        }

        &.on.group {
          border-radius: 0;
        }

        .groupundefined {

          i,
          .i-icon {
            color: #686CE8 !important;
          }
        }

        i,
        .i-icon {
          padding-right: 10px;
          color: #686CE8;
        }

        .color1 {
          color: #AFACC7;
          font-size: 12px;
        }
      }

      dd:hover {
        i {
          transform: scale(1) !important;
        }
      }
    }
  }
}
</style>
